<?php

namespace App\Logic\Auth\Form;

use App\Core\BaseForm;
use App\Core\Exception\DefaultException;
use App\Model\Auth\RoleModel;
use App\Util\UserIdentityHelper;

class RoleSaveForm extends BaseForm{
    
    public $id;
    public $name;
    public $merchants_id = 0;
    public $state = 1;
    public $type = 1;

    public function rules(){
        return [
            'name'         => ['required|notEmpty|mbLengthMax:100', '类目名称', '请输入1——100字符的内容'],
            'state'        => ['required', '是否显示', '请选择是否显示'],
        ];
    }

    protected $_info;
    
    /**
     * 校验提交数据
     * @return bool
     * @throws DefaultException
     * @throws \EasySwoole\Validate\Exception\Runtime
     */
    public function validate(){
        //生成验证器，方法自动读取rules方法返回的值数据
        $validate = $this->createValidator();

        //补充一些没法通过配置的规则，如inArray
        $booleanArr = [RoleModel::ENABLED, RoleModel::DISABLED];
        $validate->addColumn('state')->inArray($booleanArr);

        $booleanArr = [RoleModel::TYPE_INSIDE, RoleModel::ROLE_BUSINESS, RoleModel::ROLE_WAREHOUSE];
        $validate->addColumn('type')->inArray($booleanArr);

        if(!($check = $validate->validate($this->getAttributes()))){
            throw new DefaultException($validate->getError()->__toString(), 600);
        }
        
        if($this->id && empty($this->getInfo())){
            throw new DefaultException('不存在记录');
        }

        if ( !empty($this->getInfo()) && $this->getInfo()->is_action == RoleModel::DISABLED ){
            throw new DefaultException('该角色不允许编辑');
        }


        return true;
    }
    
    /**
     * 保存数据
     * @return \App\Core\Output
     * @throws DefaultException
     * @throws \EasySwoole\Mysqli\Exception\Exception
     * @throws \EasySwoole\ORM\Exception\Exception
     * @throws \EasySwoole\Validate\Exception\Runtime
     * @throws \Throwable
     */
    public function saveData(){
        $this->validate();
        
        if($this->id){
            $result = RoleModel::updateData($this->getAttributeData(['id']), ['id' => $this->id]);
        }else{
            $result = RoleModel::insertData($this->getAttributeData(['id']));
        }
        
        return $this->success(['id' => $this->id ?: $result->lastQueryResult()->getLastInsertId()]);
    }
    
    /**
     * 获取详情
     * @return \App\Core\BaseModel|array|bool|\EasySwoole\ORM\AbstractModel|\EasySwoole\ORM\Db\Cursor|\EasySwoole\ORM\Db\CursorInterface|null
     * @throws \EasySwoole\Mysqli\Exception\Exception
     * @throws \EasySwoole\ORM\Exception\Exception
     * @throws \Throwable
     */
    public function getInfo(){
        if($this->_info === null){
            $this->_info = RoleModel::getOne(['id' => $this->id]);
        }
        return $this->_info;
    }
    
}